<?php
/*
 * xDesk 2 Desktop 0.1
 * Author: Sergi Ramon Ballart
 * 
 * xDesk 2 installer
 */
 	if (file_exists('../settings.php')) {
 		include('../settings.php');
 		header('Location: '.$XDESK_CI_CONFIG['base_url']);
 		die();
 	}
 	error_reporting(E_NONE);
	if (isset($_POST['mysql_server']) &&
		isset($_POST['mysql_user']) &&
		isset($_POST['mysql_password'])) {
		$mysql = mysql_pconnect($_POST['mysql_server'], $_POST['mysql_user'], $_POST['mysql_password']);
		if ($mysql) {
			// Fail variable to controll if all gone ok
			$fail = false;
			
			// Search if there is already an xdesk2 database
			$found = false;
			$db_list = mysql_list_dbs($mysql);
			while ($row = mysql_fetch_object($db_list)) {
     			if ($row->Database == 'xdesk2') {
     				$found = true;
     			}
			}
			// If not, create it
			if (!$found) {
				mysql_query('CREATE DATABASE xdesk2', $mysql);
			}
			// Select the xdesk2 database
			mysql_select_db('xdesk2', $mysql);
			
			// Create modules table
			$sql = file_get_contents('sql/xdesk2_modules.sql');
			if ($sql) {
				//$sql = explode(";##NWL##", str_replace("\n",'##NWL##',$sql));
				$sql = explode(";\r\n", $sql);
				foreach ($sql as $query) {
					if (trim($query) != '') {
						mysql_query($query, $mysql);
					}
				}
			} else {
				$fail = true;
			}
			
			// Get config file template contents
			$config = file_get_contents('settings.template.php', 'r');
			
			// Setup config contents
			$config = str_replace('##BASEURL##', $_POST['base_url'], $config);
			
			// Save the configured settings file (this disables /install from running!)
			if (!file_put_contents('../settings.php', $config))
				$fail = true;
			
			if (!$fail)
				die('{"success":true}');
		}
	}
	echo '{"success":false}';
?>